<?php

namespace app\api\controller\wanlshop;

use app\api\extra\CommonCode;
use app\api\model\wanlshop\find\user;
use app\common\controller\Api;
use think\Log;
use think\Db;


class Timedscript extends api{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function UpdateLights(){
        //防超时设置
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        ini_set("display_errors", "On");
        error_reporting(E_ALL | E_STRICT);
        ini_set("max_execution_time", "500000");
        ignore_user_abort(true);

        //现在时间
        $time = time();
        //获取过去33天时间戳
        $time_33 = $time - 86400 * 33;
//        $time_33 = $time + 86400 * 33;
        //根据条件查询用户信息
        //查询用户信息
        $get_light_list = db("user")->where("createtime","<",$time_33)->order("id")->field("id,lamp,lamp_update_time,first_lamp_time,createtime")->select();
        //定义亮灯 灭灯数组
        $open_light_first = $open_light = $close_light = [];
        foreach($get_light_list as $v){
            $where = [];
            $level = 0;
            $juniorArr = [];
            //判断用户现在状态
            if($v["lamp"] == 0){
                if($v["first_lamp_time"] == null){
                    $user_time = $v["createtime"];
                }else{
                    $user_time = $v["first_lamp_time"];
                }
            }elseif($v["lamp"] == 1){
                $user_time = $v["first_lamp_time"];
            }
            if($user_time >= $user_time + 86400 * 33 && $user_time < $user_time + 86400 * 66){
                $level = 1;
                $juniorArr = $this->GetMyJunior($v["id"],$level);
                $where["first_lamp_time"] = ["between",[$user_time + 86400 * 33,$user_time + 86400 * 66]];
            }elseif($user_time >= $user_time + 86400 * 66 && $user_time < $user_time + 86400 * 99){
                $level = 2;
                $juniorArr = $this->GetMyJunior($v["id"],$level);
                $where["first_lamp_time"] = ["between",[$user_time + 86400 * 66,$user_time + 86400 * 99]];
            }elseif($user_time >= $user_time + 86400 * 99){
                $level = 3;
                $juniorArr = $this->GetMyJunior($v["id"],$level);
                $where["first_lamp_time"] = [">",$user_time + 86400 * 99];
            }
            $count_user = db("user")->where("id","in",$juniorArr)->where($where)->count();
            if($level == 1){
                if($v["lamp"] == 0){
                    if($v["first_lamp_time"] == null){
                        if ($count_user >= 3){
                            $open_light_first[] = $v["id"];
                        }
                    }else{
                        if ($count_user >= 3){
                            $open_light[] = $v["id"];
                        }
                    }
                }elseif($v["lamp"] == 1){
                    if ($count_user < 3){
                        $close_light[] = $v["id"];
                    }
                }
            }elseif($level == 2){
                if($v["lamp"] == 0){
                    if($v["first_lamp_time"] == null){
                        if ($count_user >= 9){
                            $open_light_first[] = $v["id"];
                        }
                    }else{
                        if ($count_user >= 9){
                            $open_light[] = $v["id"];
                        }
                    }
                }elseif($v["lamp"] == 1){
                    if ($count_user < 9){
                        $close_light[] = $v["id"];
                    }
                }
            }elseif($level == 3){
                if($v["lamp"] == 0){
                    if($v["first_lamp_time"] == null){
                        if ($count_user >= 27){
                            $open_light_first[] = $v["id"];
                        }
                    }else{
                        if ($count_user >= 27){
                            $open_light[] = $v["id"];
                        }
                    }
                }elseif($v["lamp"] == 1){
                    if ($count_user < 27){
                        $close_light[] = $v["id"];
                    }
                }
            }
        }
        // 更新用户亮灯灭灯状态
        Db::startTrans();
        try {
            db("user")->where("id","in",$open_light_first)->update(["lamp"=>1,"first_lamp_time"=>$time,"lamp_update_time"=>$time]);
            db("user")->where("id","in",$open_light)->update(["lamp"=>1,"lamp_update_time"=>$time]);
            db("user")->where("id","in",$close_light)->update(["lamp"=>0,"lamp_update_time"=>$time]);
            Log::log("初次亮灯:" . json_encode($open_light_first));
            Log::log("再次亮灯:" . json_encode($open_light));
            Log::log("灭灯:" . json_encode($close_light));
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("错误原因:" . $e->getMessage());
            return false;
        }
        $this->success("更新亮灯数据完成");
    }

    //获取当前用户底下所有下级
    public function GetMyJunior($id,$level){
        $level1 = db("user")->where("direct_push",$id)->column("id");
        if($level == 1){
            return $level1;
        }elseif($level == 2){
            $id_arr = db("user")->where("direct_push","in",$level1)->column("id");
            return $id_arr;
        }elseif($level == 3){
            $level2 = db("user")->where("direct_push","in",$level1)->column("id");
            $id_arr = db("user")->where("direct_push","in",$level2)->column("id");
            return $id_arr;
        }else{
            return false;
        }
    }

    //自动完成收货
    public function OrderAutoUpdate(){
        echo "开始执行订单状态自动更新任务..." . "\n";

        $sevenDaysAgo = time() - (7 * 24 * 60 * 60); // 修正变量名

        // 查询需要更新的订单
        $orders = db("wanlshop_order")
            ->where('state', '3')
            ->where('delivertime', '<=', $sevenDaysAgo)
            ->where('deletetime is null')
            ->select();

        if (empty($orders)) {
            $this->error("没有需要更新的订单...");
        }
        // 预先获取所有店铺对应的用户ID，减少数据库查询
        $shopIds = array_column($orders, 'shop_id');
        $shopUserMap = db("wanlshop_shop")
            ->where('id', 'in', $shopIds)
            ->column('user_id', 'id');

        foreach ($orders as $order){
            Db::startTrans();
            try {
                $currentState = db("wanlshop_order")->where('id', $order["id"])->value('state');
                if ($currentState != '3') {
                    throw new \Exception("订单状态已变更，跳过处理，订单号: " . $order["order_no"]);
                }

                $discounts_money = db("user_balance_log")->where("order_id", $order["id"])->sum("discounts_money");
                db("user_balance_log")->where("order_id", $order["id"])->update(["status"=>1, "updatetime"=>time()]);

                // 使用预先获取的用户ID映射
                $userId = $shopUserMap[$order["shop_id"]] ?? 0;
                if(empty($userId)){
                    throw new \Exception("未找到店铺对应的用户，订单号: " . $order["order_no"]);
                }

                db("user")->where("id", $userId)->setInc("balance", $discounts_money);

                $orderUpdate = db("wanlshop_order")->where('id', $order["id"])->update([
                    'state' => '4',
                    'updatetime' => time(),
                    'taketime' => time()
                ]);

                if ($orderUpdate === false) {
                    throw new \Exception("更新订单状态失败，订单号: " . $order["order_no"]);
                }

                Db::commit();
                echo "更新的订单号: " . $order["order_no"] . "\n";
            } catch (\Exception $e) {
                Db::rollback();
                Log::error("订单处理错误，订单号: " . $order["order_no"] . "，错误原因:" . $e->getMessage());
            }
        }
        $this->success("订单状态自动更新任务执行完毕");
    }


    //等级更新脚本
    public function repurchaseList(){
        $userList = db("user")->where('lamp',1)->select();
        foreach ($userList as $v){

        }

    }

    //更新盲盒信息
    public function updateUserBlindInfo(){
        $times = db("user")->where('blind_times',34)->dec("blind_times")->update(["updatetime"=>time()]);
        $now = strtotime(date("Ymd"));
        $blindList = db("user_blind_log")->where("blindtime","<",$now)->select();
        $score = 0;
        $id_arr = [];
        foreach ($blindList as $v){
            $score = bcadd($score,bcsub($v['money'],$v['use_money'],2),2);
            $id_arr[] = $v["id"];
        }
        $once_score = bcdiv($score,33,2);
        for($i = 1;$i < 34 ; $i ++){
            $l_now = $now + 86400 * $i;
            db("user_blind_log")->where("blindtime",$l_now)->inc("money",$once_score)->update(["updatetime"=>time()]);
        }
        $delete_times = db("user_blind_log")->where("id","in",$id_arr)->delete();
        $this->success("完成",["更新用户盲盒次数"=>$times,"更新未抽盲盒总积分"=>$score,"更新未抽盲盒单次积分"=>$once_score,"删除过期盲盒"=>$delete_times]);
    }



}
